package utils;

import java.io.File;
import java.io.Serializable;
import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.digest.Md5Crypt ;


public class AesUtil implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private static final String AESTYPE = "AES/ECB/PKCS5Padding";
	public static final String KEY = "99012345678901234567890123456789";
	
	public static String AES_Encrypt(String keyStr, String plainText) throws Exception {
		byte[] encrypt = null;
		Key key = generateKey(keyStr);
		Cipher cipher = Cipher.getInstance(AESTYPE);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		encrypt = cipher.doFinal(plainText.getBytes());
		return Base64.getEncoder().encodeToString(encrypt);
	}

	public static String AES_Decrypt(String keyStr, String encryptData) throws Exception {
		byte[] decrypt = null;
		Key key = generateKey(keyStr);
		Cipher cipher = Cipher.getInstance(AESTYPE);
		cipher.init(Cipher.DECRYPT_MODE, key);
		decrypt = cipher.doFinal(Base64.getDecoder().decode(encryptData));
		return new String(decrypt).trim();
	}
	
	public static String AES_DecryptFile(File keyStr) throws Exception {
		return null;
	}

	private static Key generateKey(String key) throws Exception {
		SecretKeySpec keySpec = new SecretKeySpec(HexString2Bytes(key), "AES");
		return keySpec;
	}

	private static byte uniteBytes(byte src0, byte src1) {
		byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
		byte ret = (byte) (_b0 | _b1);
		return ret;
	}

	public static byte[] HexString2Bytes(String src) {
		byte[] ret = new byte[src.length() / 2];
		byte[] tmp = src.getBytes();
		for (int i = 0; i < src.length() / 2; ++i) {
			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
		}
		return ret;
	}

	public static void main(String[] args) throws Exception{
		try {
			//String s="dr+XCNcyAOOMVSw+6xJ4GznoAHJrAIOADTnQTcdCEDc=";
			String key=DigestUtil.md5 ( "A5h7EF0I" );
			System.out.println(AES_Decrypt(key, "dIic/uUVmKy8jR72fsRWFW9XY3AUNrRyMMgoLKJSkaM="));
			//System.out.println(AES_Encrypt(key, AES_Decrypt(key, s)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}